package com.demo.function.jdk.lambda;

import com.alibaba.fastjson.JSON;
import com.demo.model.dto.OrderHeader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

@Slf4j
public class LambdaFunction {

    /**
     * 排序
     */
    public void sort() {

        List<OrderHeader> list = getOrders();
        log.info("LambdaFunction.sort 排序前 MobileTel:{}", JSON.toJSONString(list));
        list.sort(comparing("asc", OrderHeader::getMobileTel));
        log.info("LambdaFunction.sort 排序后 MobileTel:{}", JSON.toJSONString(list));

        list = getOrders();
        log.info("LambdaFunction.sort 排序前 orderId:{}", JSON.toJSONString(list));
        list.sort(comparing("desc", OrderHeader::getOrderId));
        log.info("LambdaFunction.sort 排序后 orderId:{}", JSON.toJSONString(list));
    }

    private List<OrderHeader> getOrders() {
        List<OrderHeader> list = new ArrayList<>();

        OrderHeader orderHeader = new OrderHeader();
        orderHeader.setOrderId(1L);
        orderHeader.setMobileTel("13800138000");
        list.add(orderHeader);

        orderHeader = new OrderHeader();
        orderHeader.setOrderId(2L);
        orderHeader.setMobileTel("13800138000");
        list.add(orderHeader);

        orderHeader = new OrderHeader();
        orderHeader.setOrderId(3L);
        orderHeader.setMobileTel("13800138001");
        list.add(orderHeader);
        return list;
    }

    private <T, U extends Comparable<? super U>>Comparator<T> comparing(String isAsc, Function<T, U> keyExtractor) {
        if (StringUtils.equals(isAsc, "asc")) {
            return Comparator.comparing(keyExtractor);
        } else {
            return Comparator.comparing(keyExtractor).reversed();
        }
    }
}
